package com.xlong.component.task;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xlong.BeanEntity.TaskEntity;
import com.xlong.core.CommUtils;
import com.xlong.core.PropertiesConfig;
import com.xlong.taskthread.ConsumerThread;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class TaskExecute {
	@Autowired
    private TaskQueue taskQueue;
	
	@Autowired
	private PropertiesConfig pconfig;

    private ThreadPoolExecutor consumerPool =
            new ThreadPoolExecutor(100,100,60, TimeUnit.MILLISECONDS,new ArrayBlockingQueue(1000),new ThreadPoolExecutor.AbortPolicy());

    //初始化
    @PostConstruct
    public void init() {
        log.info("开始持续处理任务");
        new Thread(this::execute).start();
    }

    /**
     * 持续处理
     * 返回执行结果
     */
    @SuppressWarnings("static-access")
	@SneakyThrows
    private void execute() {
    	//测试读取配置文件属性
    	log.info("arg1:" + pconfig.getTestarg1());
    	log.info("arg2:" + pconfig.getTestarg2());
        while (true) {
            try {
                //取出任务
                TaskEntity task;
                task = taskQueue.getInstance().take();
                //int time = 1;
                if (task != null) {
                    // 如果有任务就分配线程去处理
                    consumerPool.execute(new ConsumerThread(task));
                }else {
                	//让当前线程从运行状态 转为 就绪状态，以允许具有相同优先级的其他线程获得运行机会
                	Thread.yield();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error(e.getMessage());
            }
        }
    }
}
